//
//  MemberfindIntegralListViewController.m
//  HAODE
//
//  Created by panquanReabam.com on 15/9/26.
//  Copyright (c) 2015年 reabam.com. All rights reserved.
//

#import "MemberAddressViewController.h"
#import "OrderDetailViewController.h"
#import "MemberListViewController.h"
#import "MJRefresh.h"
#import "MemberAddressCell.h"
#import "AddOrEditAddressViewController.h"
#import "MemberAddressModel.h"
@interface MemberAddressViewController ()<MBProgressHUDDelegate,UIGestureRecognizerDelegate,UINavigationControllerDelegate,UITextFieldDelegate,UISearchBarDelegate,UIAlertViewDelegate,MemberAddressCellDelegate>
@property(nonatomic,strong)NSString*addressID;
@end

@implementation MemberAddressViewController

{

    MJRefreshHeaderView* _header;
    MJRefreshFooterView* _footer;
    NSMutableArray* modelArray;
    int pageNumber;
    MBProgressHUD *progressHud;
    NSString*TotalCount;
    UITableView*table;
   
}
@synthesize alt = alt;
@synthesize delegate;
-(void)BackAction:(UIButton *)sender{
   //    [self.delegate MemberAddressViewController:self memberIdStr:self.memberId userName:self.userName phone:self.phone sex:self.sex consigneeName:ScreeningModel.name consigneeAddr:
//     [NSString stringWithFormat:@"%@%@%@%@",ScreeningModel.provinceName, ScreeningModel.cityName, ScreeningModel.regionName,ScreeningModel.address]  consigneePhone:ScreeningModel.phone];
   
    
    [self.navigationController popViewControllerAnimated:YES];
    
}
- (void)viewDidDisappear:(BOOL)animated

{
    
    [super viewDidDisappear:animated];
    self.navigationController.delegate = nil;
    
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self requestData];
    
}

- (void)viewDidLoad
{
    
    [super viewDidLoad];
    [self setNavigation];

    UIButton*addBtn=[[UIButton alloc]initWithFrame:CGRectMake(0, ScreenHeight-48, ScreenWidth, 48)];
    [addBtn setTitle:@"+  新增收货地址" forState:UIControlStateNormal];
    addBtn.backgroundColor=luseColor;
    [addBtn addTarget:self action:@selector(adds:) forControlEvents:UIControlEventTouchUpInside];
    [addBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    NSMutableAttributedString *AttributedStr = [[NSMutableAttributedString alloc]initWithString:@"+  新增收货地址"];
    
    [AttributedStr addAttribute:NSFontAttributeName
     
                          value:[UIFont systemFontOfSize:24]
     
                          range:NSMakeRange(0, 1)];
    
    [AttributedStr addAttribute:NSForegroundColorAttributeName
     
                          value:[UIColor whiteColor]
     
                          range:NSMakeRange(0, 1)];
    addBtn.titleLabel.attributedText = AttributedStr;
    [self.view addSubview:addBtn];
    
}

-(void)adds:(UIButton*)sender{

   
    AddOrEditAddressViewController *detailViewController = [[AddOrEditAddressViewController alloc] init];
    detailViewController.memberId=self.memberId;
    detailViewController.editType=@"A";
    [self.navigationController pushViewController:detailViewController animated:YES];

}

-(void)requestData{
    modelArray= [[NSMutableArray alloc] init];
    table = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, ScreenWidth, ScreenHeight-64-48) style:UITableViewStylePlain];
    table.delegate = self;
    table.dataSource = self;
    table.separatorStyle=UITableViewCellSeparatorStyleNone;
    [table registerClass:[MemberAddressCell class] forCellReuseIdentifier:@"MemberAddressViewController"];
    [self.view addSubview:table];

    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString* Token = [user objectForKey:@"tokenId"];
    if (Token ==nil) {
        Token=@"dd";
    }
    NSMutableDictionary *param = [NSMutableDictionary new];
    [param setValue:Token forKey:@"tokenId"];
    [param setValue:@"1" forKey:@"pageIndex"];
    [param setValue:@"20" forKey:@"pageSize"];
    [param setValue:self.memberId forKey:@"memberId"];
    
    
    [Global showIndeterminateHudSub:@"加载中，请稍后。。。" delay:30 view:self.view];
    
    [HttpRequest requestData:@"Business/Member/Address" params:param success:^(BOOL isSuccess, SeverData *severDataDict) {
        if (isSuccess) {
            
            NSLog(@"====%@",severDataDict.dataDict);
            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                [Global hideProgressHUDInternal:self.view];
         
                TotalCount=[severDataDict.dataDict objectForKey:@"totalIntegral"];
                NSMutableArray * mItemsArray=[NSMutableArray arrayWithArray:[severDataDict.dataDict objectForKey:@"DataLine"]];
                for (NSDictionary *dic in mItemsArray) {
                    MemberAddressModel *dataModel=[MemberAddressModel dataModelWithDict:dic];
                    [modelArray addObject:dataModel];
                }
                
                [table reloadData];
                
        
                
            }else{
                [Global hideProgressHUDInternal:self.view];
                
            }
            
        }
        else
        {
            [Global hideProgressHUDInternal:self.view];
            [Global showTextHudSub:severDataDict.resultStr view:self.view];
        }
        
    }];

    
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [modelArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    MemberAddressCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MemberAddressViewController"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.index=[NSString stringWithFormat:@"%ld",indexPath.row];
    cell.model=modelArray[indexPath.row];
    cell.mDelegate=self;
   
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    
    MemberAddressModel *ScreeningModel=modelArray[indexPath.row];
   
    if ([self.chooseState isEqualToString:@"选择"]) {
        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
        NSString* Token = [user objectForKey:@"tokenId"];
        NSMutableDictionary *param = [NSMutableDictionary new];
        [param setValue:Token forKey:@"tokenId"];
        
        [param setValue:ScreeningModel.addressId forKey:@"addressId"];
        [Global showIndeterminateHudSub:@"加载中，请稍后。。。" delay:30 view:self.view];
        [HttpRequest requestData:@"Business/Member/setDefaultAddress" params:param success:^(BOOL isSuccess, SeverData *severDataDict) {
            if (isSuccess) {
                
                NSLog(@"====%@",severDataDict.dataDict);
                if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                    [Global hideProgressHUDInternal:self.view];
                    
                }else{
                    [Global hideProgressHUDInternal:self.view];
                    }
                }
            else
            {
                [Global hideProgressHUDInternal:self.view];
                [Global showTextHudSub:severDataDict.resultStr view:self.view];
            }
            
        }];
        [self.delegate MemberAddressViewController:self memberIdStr:self.memberId userName:self.userName phone:self.phone sex:self.sex consigneeName:ScreeningModel.name consigneeAddr:
         [NSString stringWithFormat:@"%@%@%@%@",ScreeningModel.provinceName, ScreeningModel.cityName, ScreeningModel.regionName,ScreeningModel.address]  consigneePhone:ScreeningModel.phone];
        [self.navigationController popViewControllerAnimated:YES];

    }else{
 
    }
   
}

-(void)edit:(NSString*)sender{

    MemberAddressModel *model=modelArray[sender.intValue];
    AddOrEditAddressViewController *detailViewController = [[AddOrEditAddressViewController alloc] init];
    detailViewController.name=model.name;
    detailViewController.phone=model.phone;
    detailViewController.provinceName=model.provinceName;
    detailViewController.cityName=model.cityName;
    detailViewController.regionName=model.regionName;
    detailViewController.isDefault=model.isDefault;
    detailViewController.addressId=model.addressId;
    detailViewController.address=model.address;
    detailViewController.memberId=self.memberId;
    detailViewController.editType=@"U";
    [self.navigationController pushViewController:detailViewController animated:YES];
 
}
-(void)deleteBtn:(NSString*)sender{
    
    
    UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"确认删除" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消" ,nil];
    [alert show];
    MemberAddressModel *model=modelArray[sender.intValue];
    self.addressID=[NSString stringWithFormat:@"%@" ,model.addressId];

}
#pragma mark UIActionSheetDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    
    if (buttonIndex == 0) {
        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
        NSString* Token = [user objectForKey:@"tokenId"];
        NSMutableDictionary *param = [NSMutableDictionary new];
        [param setValue:Token forKey:@"tokenId"];
        [param setValue:@"D" forKey:@"editType"];
        [param setValue:self.memberId forKey:@"memberId"];
        [param setValue:self.addressID forKey:@"addressId"];
        NSLog(@"====%@",param);
        [Global showIndeterminateHudSub:@"加载中，请稍后。。。" delay:30 view:self.view];
        
        
        [HttpRequest requestData:@"Business/Member/editAddress" params:param success:^(BOOL isSuccess, SeverData *severDataDict) {
            if (isSuccess) {
                
                NSLog(@"====%@",severDataDict.dataDict);
                if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                    [Global hideProgressHUDInternal:self.view];
                    
                    [self requestData];
                    
                }else{
                    [Global hideProgressHUDInternal:self.view];
                    
                }
                
            }
            else
            {
                [Global hideProgressHUDInternal:self.view];
                
                [Global showTextHudSub:severDataDict.resultStr view:self.view];
            }
            
        }];

    } else if (buttonIndex == 1) {
       
    
    
    
    }
}


-(void)theDefaultBtn:(NSString*)sender{
    
    MemberAddressModel *model=modelArray[sender.intValue];
    
    self.addressID=[NSString stringWithFormat:@"%@" ,model.addressId];
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString* Token = [user objectForKey:@"tokenId"];
    if (Token ==nil) {
        Token=@"dd";
    }
    NSMutableDictionary *param = [NSMutableDictionary new];
    [param setValue:Token forKey:@"tokenId"];
   
    [param setValue:self.addressID forKey:@"addressId"];
    
     NSLog(@"====%@",param);
    [Global showIndeterminateHudSub:@"加载中，请稍后。。。" delay:30 view:self.view];
    
    
    [HttpRequest requestData:@"Business/Member/setDefaultAddress" params:param success:^(BOOL isSuccess, SeverData *severDataDict) {
        if (isSuccess) {
            
            NSLog(@"====%@",severDataDict.dataDict);
            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                [Global hideProgressHUDInternal:self.view];
              
                [self requestData];
         
      
            }else{
                [Global hideProgressHUDInternal:self.view];
                
            }
            
        }
        else
        {
            [Global hideProgressHUDInternal:self.view];
            
            [Global showTextHudSub:severDataDict.resultStr view:self.view];
        }
        
    }];
    

}



- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return 150;
}

#pragma mark - Table view delegate

- (void)showAlertWait
{
    alt = [[UIAlertView alloc] initWithTitle:@"网络不稳定 ！" message:@"请确认网络" delegate:self cancelButtonTitle:nil otherButtonTitles: nil];
    [alt show];
    
    [self performSelector:@selector(hideAlert) withObject:nil afterDelay:1.0f];
    
}

- (void)showAlertMessage:(NSString *)msg
{
    alt = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:msg delegate:nil cancelButtonTitle:nil otherButtonTitles: nil];
    [alt show];
    
    [self performSelector:@selector(hideAlert) withObject:nil afterDelay:1.0f];
}
- (void)hideAlert
{
    if (alt != nil)
    {
        [alt dismissWithClickedButtonIndex:0 animated:YES];
        alt = nil;
    }
}
- (void)setNavigation
{
    
    [[self rdv_tabBarController] setTabBarHidden:YES];
    self.navigationController.navigationBarHidden=NO;
    self.navigationController.navigationBar.barStyle = UIBaselineAdjustmentNone;
    UILabel *lineLabel=[[UILabel alloc] initWithFrame:CGRectMake(0, 43,ScreenWidth, 1)];
    [lineLabel setBackgroundColor:[UIColor colorWithRed:238.0/255.0 green:238.0/255.0 blue:238.0/255.0 alpha:1.0]];
    [self.navigationController.navigationBar addSubview:lineLabel];
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    [[UINavigationBar appearance] setBarTintColor:Color];
    
    UIImage* backImage = [UIImage imageNamed:@"fanhui"];
    CGRect backframe = CGRectMake(0,0,30,30);
    UIButton* backButton= [[UIButton alloc] initWithFrame:backframe];
    [backButton setBackgroundImage:backImage forState:UIControlStateNormal];
    backButton.titleLabel.textAlignment=NSTextAlignmentLeft;
    [backButton addTarget:self action:@selector(BackAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    self.navigationController.delegate = self;
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
    
    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.shadowImage = [[UIImage alloc] init];
    
    self.title=@"地址管理";
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                                                     [UIColor blackColor],
                                                                     UITextAttributeTextColor,
                                                                     [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:1],
                                                                     UITextAttributeTextShadowColor,
                                                                     [NSValue valueWithUIOffset:UIOffsetMake(0, 0)],
                                                                     UITextAttributeTextShadowOffset,
                                                                     [UIFont fontWithName:@"Helvetica Neue" size:tetlefot],
                                                                     UITextAttributeFont,nil]];
    
}

@end

